<?php
/** 根据question_id获取题目的信息。
 * Created by PhpStorm.
 * User: yaosj
 * Date: 15-7-15
 * Time: 下午9:23
 */

class GetQuestionInfo implements iController {

    public function output($queryArgs) {

        $qId = $queryArgs['question_id'];
        if (empty($qId) || !is_numeric($qId))
            return genOutput(1000);
       return genOutput(1,array('question_info' => $this ->  getQuestionById($qId)));

    }

    private function getQuestionById($qId) {
        global $cmsdb;
        
        $sql = 'SELECT az.* ,p.name source FROM '.$cmsdb->oZtkQuestions.' az,relation_ztk_paper_question r,original_ztk_papers p
            WHERE r.question_id = az.id AND r.paper_id = p.id AND az.id = :mId';
        $mQuestion = $cmsdb->getRow($sql, array(':mId' => $qId));

        if (empty($mQuestion))
            return null;

        $category = array();
        $cat = $cmsdb->getResults("SELECT * FROM dp_conf_question_category WHERE 1");
        foreach ($cat as $c) {
            $category["$c->category_id"] = $c->category_name;
            $category["$c->category_name"] = $c->category_id;
        }

        $options = unserialize($mQuestion->options);
        $noteInfo = getNotesByQuestions($mQuestion->id);

        return array(
            'id' => intval($mQuestion->id),
            'material' => $this->html2text(getMaterialById($mQuestion->material_id)),
            'content'  => $this->html2text($mQuestion->question),
            'option_A' => $this->html2text(ltrim($options[0], 'A.')),
            'option_B' => $this->html2text(ltrim($options[1], 'B.')),
            'option_C' => $this->html2text(ltrim($options[2], 'C.')),
            'option_D' => $this->html2text(ltrim($options[3], 'D.')),
            'answer'   => $mQuestion->answer,
            'analysis' => $this->html2text($mQuestion->analysis),
            'note_id'  => intval($mQuestion->note_id),
            'note_ids' => !empty($noteInfo) ? $noteInfo[$mQuestion->id]['id'] : [],
            'note_name'=> !empty($noteInfo) ? $noteInfo[$mQuestion->id]['name'] : "",
            'source'   => $mQuestion->source,
            'cat_name' => $mQuestion->category,
            'cat_id'   => intval($category["$mQuestion->category"])
        );
    }

    /**
     * 网站题目对img标签的处理和app中不一样
     * @param $str
     * @return string
     */
    private function  html2text($str) {

      if (empty($str))
          return '';

        $str = str_replace('&nbsp;', ' ', $str);
        $str = html_entity_decode(trim($str));
        $str = strip_tags($str, '<img><p><br>');

        $str = preg_replace("/<p[^>]*>/", "\n", $str);
        $str = str_replace("</p>", "\n", $str);
        $str = str_replace(array('<br>', '<br/>', '<br />'), "\n", $str);

        //处理img标签
        //$pattern = "/<img.*?src\=[\"'](.*?)[\"'][^>]*>/";
        //$str = preg_replace($pattern, "<img=\${1}></img>", $str);

        return trim($str);
    }
}